package cn.cocho.android.mc.comp.listview;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;

import cn.cocho.android.mc.R;

import cn.cocho.android.mc.base.Page;
import cn.cocho.android.mc.base.ResourcesUtils;
import cn.cocho.android.mc.comp.listview.McListView.OnStateChangeListener;
import cn.cocho.android.mc.comp.listview.McListView.State;
import cn.cocho.android.mc.log.LoggerUtils;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseListViewAdapter<T> extends BaseAdapter {

    public McListView listView;

    private Page<T> page;

    protected List<T> itemList;

    /**
     * 1:重新加载数据;0:追加数据
     */
    public static final int reloadData = 1, appendData = 0;

    Handler loadDataHandler = null;

    public BaseListViewAdapter(final McListView listView) {
        super();
        this.listView = listView;
        itemList = new ArrayList<T>();
        initListener();
        initHandler();
    }

    private void initListener() {
        listView.setOnStateChangeListener(new OnStateChangeListener() {
            @Override
            public void stateChanged(McListView listView, State newState) {
                if (newState == State.LOADING) {
                    updateData(true);
                }
            }

        });

        listView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {// 判断滑动是否停下
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {// 判断是否滚动到底部
                        /**
                         * huasenxiu
                         *
                         * 2014年11月20日17:04:11
                         *
                         *增加page不为空的判断，该bug曾导致当listview滑动到底部时，出现空指针异常
                         *
                         */
                        if (page != null && page.isHasNext()) {
                            listView.updateFooter(ResourcesUtils.getString(R.string.listview_loading), false);
                            updateData(false);
                        } else {
                            listView.updateFooter(ResourcesUtils.getString(R.string.listview_load_more), true);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        listView.footerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listView.updateFooter(ResourcesUtils.getString(R.string.listview_loading), false);
                updateData(false);
            }
        });
    }

    private void initHandler() {
        loadDataHandler = new Handler() {
            public void handleMessage(Message msg) {
                try {
                    updateItemData(msg);
                    updateMainView(msg);
                } catch (Exception e) {
                    LoggerUtils.error(this.getClass().getName(), e);
                } finally {
                    if (page != null) {
                        if (page.isHasNext()) {
                            listView.updateFooter(ResourcesUtils.getString(R.string.listview_load_more), false);
                        } else {
                            listView.updateFooter(ResourcesUtils.getString(R.string.listview_load_more), true);
                        }
                    }
                    listView.updateState(State.DONE);
                }
            }
        };
    }

    public void updateData(final boolean reload) {
        if (reload) {
            if (listView.getFooterViewsCount() > 0) {
                listView.removeFooterView(listView.footerView);
            }
            listView.updateState(State.LOADING);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                Object data = loadData(getPage(reload));
                Message message = Message.obtain();
                message.obj = data;
                message.what = reload ? reloadData : appendData;
                loadDataHandler.sendMessage(message);
            }
        }).start();

    }

    @SuppressWarnings("unchecked")
    protected void updateItemData(Message msg) {
        page = (Page<T>) msg.obj;
        int what = msg.what;
        if (what == reloadData) {
            itemList.clear();
        }
        if (page != null) {
            List<T> rows = page.getRows();
            if (rows != null) {
                itemList.addAll(rows);
            }
        }

        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (itemList.size() == 0) {
            if (listView.getFooterViewsCount() > 0) {// 当没有数据显示的时候，移除listview底部加载更多按钮
                listView.removeFooterView(listView.footerView);
            }
            listView.setDivider(null);
            listView.setFooterDividersEnabled(false);// 数据不存在时，隐藏listview默认的分割线
            View emptyView = listView.getEmptyView();
            emptyView.setClickable(false);// 空页面的时候禁掉点击事件，否则重写了OnItemClick的时候，点击空页面会出错
            emptyView.setLayoutParams(new AbsListView.LayoutParams(listView.getWidth(), listView.getHeight()));// 使空页面居中显示
            return emptyView;
        } else {
            if (convertView == listView.getEmptyView()) {
                convertView = null;
            }
            listView.setFooterDividersEnabled(true);// 数据存在时，添加listview默认的分割线
            return getItemView(position, convertView, parent);
        }

    }

    @Override
    public boolean isEnabled(int position) {
        if (itemList.size() == 0) {// 当listView没有记录的时候禁用掉OnItemClick
            return false;
        }
        return super.isEnabled(position);
    }

    private Page<T> getPage(boolean reload) {
        if (page == null) {
            page = new Page<T>();
            page.setPageSize(listView.getPageSize());
        }

        if (reload) {
            page.setPageNo(1);
        } else {
            page.setPageNo(page.getPageNo() + 1);
        }
        return page;
    }

    @Override
    public int getCount() {
        if (itemList.size() == 0) {
            return 1;
        }
        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
        if (itemList.size() == 0) {
            return null;
        }
        return itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        if (itemList.size() == 0) {
            return 1;
        }
        return position;
    }

    public void setPage(Page<T> page) {
        this.page = page;
    }

    public abstract Page<T> loadData(Page<T> page);

    protected abstract void updateMainView(Message msg);

    protected abstract View getItemView(int position, View convertView, ViewGroup parent);

}
